// 商品详情页面的逻辑

// 获取元素
const imgBox = document.querySelector('.show > img')
const titleBox = document.querySelector('.title')
const priceBox = document.querySelector('.price')
const descBox = document.querySelector('.desc')
const contentBox = document.querySelector('.content')
let leftimg = document.querySelector('.enlarge>img')

// 首先要拿到商品的id
const goodsId = window.sessionStorage.getItem('goodsId')
    // 发送请去后去数据
setItem()
async function setItem() {
    let res = await pAjax({
        url: 'http://localhost:8888/goods/item',
        data: { id: goodsId },
        datatype: 'json'
    })
    console.log(res);

    imgBox.src = res.info.img_big_logo
    leftimg.src = res.info.img_big_logo
    leftimg.style.width = 800 + 'px'
    titleBox.innerText = res.info.title
    priceBox.innerText = `￥${res.info.price}`
    descBox.innerHTML = res.info.goods_introduce
}

// 点击加入购物车 能把商品加入到购物车中
contentBox.addEventListener('click', (e) => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.nodeName === 'BUTTON') {

        addCart(target.dataset.id)
    }
})
async function addCart() {

    // 首先要判断是不是处于登录状态
    const id = window.localStorage.getItem('id')
    const token = window.localStorage.getItem('token')
    if (!id || !token) {
        if (window.confirm('您还没有登录,点击取消留在本页面,点击确定去登录')) {
            window.location.href = './login.html'
        }
        return
    }

    // 发送请求获取数据
    let res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        method: 'post',
        data: { id, goodsId },
        datatype: 'json',
        headers: { 'authorization': token }
    })

    if (res.code !== 1) {
        if (window.confirm('您还没有登录,点击取消留在本页面,点击确定去登录')) {
            window.location.href = './login.html'
        }
        return
    }

    // 说明成功
    alert('恭喜您添加购物车成功')
    console.log(res);

}